package com.panfeng.xcloud.component.trace.config;

import brave.http.HttpTracing;
import brave.servlet.TracingFilter;
import brave.spring.webmvc.TracingHandlerInterceptor;
import com.panfeng.xcloud.component.trace.filter.NotFilter;
import com.panfeng.xcloud.component.trace.properties.ZipkinTraceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.List;

/**
 * zipkin Trace 调用链自动配置
 * @author xiaobo
 * @version 1.0
 * @since 2018-08-21
 */
@Slf4j
public class ZipkinTraceAutoConfig extends WebMvcConfigurerAdapter{

	@Autowired
	private ZipkinTraceProperties zipkinTraceProperties;

	@Autowired
	private TracingHandlerInterceptor tracingHandlerInterceptor;

	@Autowired
	private TracingFilter tracingFilter;

	/**
	 * 对filter进行拦截
	 *
	 * @param httpTracing
	 * @return
	 */
	@Bean
	public FilterRegistrationBean tracingFilter(HttpTracing httpTracing){
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		if(null != zipkinTraceProperties && zipkinTraceProperties.isEnabled()){
			filterRegistrationBean.setFilter(tracingFilter);
			log.info(">>> 已经初始化TracingFilter：{} <<<",tracingFilter);
			filterRegistrationBean.setFilter(tracingFilter);
		}else{
			Filter filter = new NotFilter();
			filterRegistrationBean.setFilter(filter);
			log.info(">>> 没有初始化TracingFilter：{} <<<",filter);
			filterRegistrationBean.setFilter(filter);
		}
		List<String> urls = new ArrayList<String>();
		urls.add("/*");
		filterRegistrationBean.setUrlPatterns(urls);
		return filterRegistrationBean;
	}

	/**
	 * 对handler进行拦截
	 *
	 * @param registry
	 * @return
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		log.info(">>> 已经初始化tracingHandlerInterceptor：{} <<<",tracingHandlerInterceptor);
		if(null != zipkinTraceProperties && zipkinTraceProperties.isEnabled()){
			log.info(">>> 已经注册tracer springmvc handler拦截器到springmvc上下文，tracingHandlerInterceptor：{} <<<",tracingHandlerInterceptor);
			registry.addInterceptor(tracingHandlerInterceptor);
		}else{
			log.info(">>> 未注册tracer springmvc handler拦截器到springmvc上下文，tracingHandlerInterceptor：{} <<<",tracingHandlerInterceptor);
		}
	}
}
